package com.cfs.chat.moudles.job;

import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description: 定时删除聊天的图片
 * @Author: fengwei-lhq
 * @Date: 2024-11-28 10:09
 **/
@Log4j2
@Component
public class ImageJob {

    /**
     * 定期删除聊天图片
     * 每3分钟执行一次
     */
    @Scheduled(fixedRate = 180000)
    public void timerToNow(){
        // Map<Long,String> img = SocketController.img;
        Map<Long,String> imgMap = new HashMap<>();
        Long now = System.currentTimeMillis() - 60000;
        Iterator<Map.Entry<Long, String>> it = imgMap.entrySet().iterator();
        int a = 0;
        while(it.hasNext()){
            Map.Entry<Long, String> entry = it.next();
            if (entry.getKey() < now){
                if (deleteFile(entry.getValue())){
                    it.remove();
                    a++;
                }
            }
        }
        log.info("删除任务执行完毕，共删除"+a+"张图片");
    }

    private boolean deleteFile(String filePath) {
        try {
            // 要删除的文件路径
            Path path = Paths.get(filePath);
            // 判文件或目录不存在
            if (Files.notExists(path)) {
                return false;
            }
            // 文件是目录
            if (Files.isDirectory(path)) {
                return false;
            }
            // 是文件
            if (Files.isRegularFile(path)) {
                return Files.deleteIfExists(path);
            }
            // 默认返回
            return false;
        } catch (IOException e) {
            log.error("文件删除异常", e);
            return false;
        }
    }

}
